﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using JKF.BusinessLayer;
using SFWS.XHandler.Core;
using JKF.Substructure;
using JKF.Entities.Model;
using JKF.Entities;
using JKF.BusinessLayer.BLL;
using System.Data;

namespace JKF.HandlerLayer.Customer
{
    public class CustomerHandler : AHttpHandler
    {
        public override void ProcessRequest()
        {
            try
            {
                Manager = Manager ?? new bllCUSTOMER();
                MemoDay = MemoDay ?? new bllCUSTOMER_MEMORIALDAY();
                Disease = Disease ?? new bllCUSTOMER_DISEASE();
                shopMgr = shopMgr ?? new bllSHOP();
                groupMgr = groupMgr ?? new bllDIC_GROUP();
                CardChangeMgr = CardChangeMgr ?? new bllCUSTOMER_CARD_CHANGE();
                this.HandleRequest(Utils.GetActionName);
            }
            catch (Exception ex)
            {
                //将错误抛到客户端(以Json格式)
                Utils.ToClient(true, ex.Message);
                AppLogger.Log(ex.Message, ex);  //写日志
            }
        }

        #region Manager
        private static bllCUSTOMER Manager;
        private static bllCUSTOMER_MEMORIALDAY MemoDay;
        private static bllCUSTOMER_DISEASE Disease;
        private static bllDIC_GROUP groupMgr;
        private static bllSHOP shopMgr;
        private static StringBuilder builder = new StringBuilder();
        private static bllCUSTOMER_CARD_CHANGE CardChangeMgr;
        #endregion

        #region Handlers
        /// <summary>
        /// 获得顾客分野数据
        /// </summary>
        public void GetCustomers()
        {
            var obj = new PagerList();
            int pageCount = 0;
            int rowCount = 0;
            var pageCurrent = 0;
            var pageSize = 20;

            pageCurrent = int.TryParse(P("PageIndex"), out pageCurrent) ? pageCurrent : 0;
            pageSize = int.TryParse(P("PageSize"), out pageSize) ? pageSize : pageSize;

            var result = Manager.GetCurstomers(P("dateStart"), P("dateEnd"), P("field"), P("fieldOp"), P("fieldKey"), P("ownShop"), bllSYS_USER.CurrentUser.USER_KEY.ToString(), pageCurrent,
                                  pageSize, ref pageCount, ref rowCount);


            if (P("isExport") != "1")
            {
                obj.Entity = null == result ? null : (from a in result.AsEnumerable()
                                                      select new
                                                      {
                                                          CUSTOMER_KEY = a.Field<Guid>("CUSTOMER_KEY").ToString(),
                                                          CARD_NO = a.Field<string>("CARD_NO"),
                                                          NAME = a.Field<string>("NAME"),
                                                          MOBILE = a.Field<string>("MOBILE"),
                                                          LEVEL_CODE = a.Field<string>("LEVEL_CODE"),
                                                          LEVEL_NAME = a.Field<string>("LEVEL_NAME"),
                                                          SHOP_NAME = a.Field<string>("SHOP_NAME"),
                                                          AVAIPOINTS = a.Field<int>("AVAIPOINTS"),
                                                          GROUP_NAME = a.Field<string>("GROUP_NAME"),
                                                          STATUS_NAME = a.Field<string>("STATUS_NAME"),
                                                          DATE_CREATE = a.Field<DateTime?>("DATE_CREATE").ToFullDateTimeFormat(),
                                                          BIRTHDAY = a.Field<DateTime?>("BIRTHDAY").ToShortDateLineFormat(),
                                                          GIVE_POINTS = a.Field<int?>("GIVE_POINTS").ToString(),
                                                          CONSUME_POINT = a.Field<int?>("CONSUME_POINTS").ToString()
                                                      }).ToList();
                obj.RowCount = rowCount;
                obj.PageCount = pageCount;
                ResponseJsonObject = obj;
            }
            else
            {
                if (result == null) return;
                result.Columns.Add("PCA", typeof(String));
                foreach (DataRow row in result.Rows)
                {
                    row["PCA"] = row["PROVINCE"] + "" + row["CITY"] + row["AREA"];
                }

                IDictionary<string, string> columns = new Dictionary<string, string>();
                columns.Add("CARD_NO", "顾客卡号");
                columns.Add("NAME", "姓名");
                columns.Add("SEX_NAME", "性别");
                columns.Add("ID_CARD", "身份证");
                columns.Add("MOBILE", "手机");
                columns.Add("PHONE", "电话");
                columns.Add("PCA", "所在地区");
                columns.Add("ADDRESS", "地址");
                columns.Add("POSTAL_CODE", "邮编");
                columns.Add("LEVEL_NAME", "顾客级别");
                columns.Add("group_NAME", "顾客分组");
                columns.Add("BIRTHDAY", "生日");
                columns.Add("AVAIPOINTS", "可用积分");
                columns.Add("DATE_CREATE", "登记时间");
                Excel.Export("顾客管理", result, columns, Response, Excel.PageType.handler);
            }
        }

        /// <summary>
        /// 获得顾客分页数据
        /// </summary>
        public void GetCustomerAdv()
        {
            var obj = new PagerList();
            var pageCount = 0;
            var rowCount = 0;
            var pageCurrent = 0;
            var pageSize = 20;
            pageCurrent = int.TryParse(P("PageIndex"), out pageCurrent) ? pageCurrent : 0;
            pageSize = int.TryParse(P("PageSize"), out pageSize) ? pageSize : pageSize;

            var advOptions = JsonSerializer.Deserialize<AdvanceSearchJson>(P("advOptions"));
            int intTmp;
            DateTime dateTmp;
            var areaCode = "";
            if (advOptions.AREA_CODE.Length > 0) areaCode = advOptions.AREA_CODE;
            else if (advOptions.CITY.Length > 4) areaCode = advOptions.CITY.Substring(0, 4);
            else if (advOptions.PROVINCE.Length > 2) areaCode = advOptions.PROVINCE.Substring(0, 2);


            var result = Manager.GetCustomerAdvPage(advOptions.CARD_NO, advOptions.LEVEL_CODE, advOptions.NAME, advOptions.SEX,
                advOptions.REFEREE_CARD, advOptions.REFEREE, advOptions.ID_CARD,
                int.TryParse(advOptions.AGEFROM, out intTmp) ? intTmp : new int?(), int.TryParse(advOptions.AGETO, out intTmp) ? intTmp : new int?(),
                advOptions.MOBILE, advOptions.PHONE, advOptions.GROUP_KEY, areaCode,
                DateTime.TryParse(advOptions.BIRTHDAYFROM, out dateTmp) ? dateTmp : new DateTime?(),
                DateTime.TryParse(advOptions.BIRTHDAYTO, out dateTmp) ? dateTmp : new DateTime?(),
                DateTime.TryParse(advOptions.DATE_CREATESTART, out dateTmp) ? dateTmp : new DateTime?(),
                DateTime.TryParse(advOptions.DATE_CREATEEND, out dateTmp) ? dateTmp : new DateTime?(),
                int.TryParse(advOptions.AVAPOINTFROM, out intTmp) ? intTmp : new int?(),
                int.TryParse(advOptions.AVAPOINTTO, out intTmp) ? intTmp : new int?(),
                bllSYS_USER.CurrentUser.USER_KEY.ToString(),
                advOptions.TITLE.Trim(),
                advOptions.FAMILY.Trim(),
                pageCurrent, pageSize, ref pageCount, ref rowCount
                );
            if (P("isExport") != "1")
            {
                obj.Entity = null == result ? null : (from a in result.AsEnumerable()
                                                      select new
                                                      {
                                                          CUSTOMER_KEY = a.Field<Guid>("CUSTOMER_KEY").ToString(),
                                                          CARD_NO = a.Field<string>("CARD_NO"),
                                                          NAME = a.Field<string>("NAME"),
                                                          MOBILE = a.Field<string>("MOBILE"),
                                                          LEVEL_CODE = a.Field<string>("LEVEL_CODE"),
                                                          LEVEL_NAME = a.Field<string>("LEVEL_NAME"),
                                                          SHOP_NAME = a.Field<string>("SHOP_NAME"),
                                                          AVAIPOINTS = a.Field<int>("AVAIPOINTS"),
                                                          GROUP_NAME = a.Field<string>("GROUP_NAME"),
                                                          STATUS_NAME = a.Field<string>("STATUS_NAME"),
                                                          DATE_CREATE = a.Field<DateTime?>("DATE_CREATE").ToFullDateTimeFormat(),
                                                          BIRTHDAY = a.Field<DateTime?>("BIRTHDAY").ToShortDateLineFormat(),
                                                          GIVE_POINTS = a.Field<int?>("GIVE_POINTS").ToString(),
                                                          CONSUME_POINT = a.Field<int?>("CONSUME_POINT").ToString()
                                                      }).ToList();
                obj.RowCount = rowCount;
                obj.PageCount = pageCount;
                ResponseJsonObject = obj;
            }
            else
            {
                if (result == null) return;
                result.Columns.Add("PCA", typeof(String));
                foreach (DataRow row in result.Rows)
                {
                    row["PCA"] = row["PROVINCE"] + "" + row["CITY"] + row["AREA"];
                }

                IDictionary<string, string> columns = new Dictionary<string, string>();
                columns.Add("CARD_NO", "顾客卡号");
                columns.Add("NAME", "姓名");
                columns.Add("SEX_NAME", "性别");
                columns.Add("ID_CARD", "身份证");
                columns.Add("MOBILE", "手机");
                columns.Add("PHONE", "电话");
                columns.Add("PCA", "所在地区");
                columns.Add("ADDRESS", "地址");
                columns.Add("POSTAL_CODE", "邮编");
                columns.Add("LEVEL_NAME", "顾客级别");
                columns.Add("group_NAME", "顾客分组");
                columns.Add("BIRTHDAY", "生日");
                columns.Add("AVAIPOINTS", "可用积分");
                columns.Add("DATE_CREATE", "登记时间");
                Excel.Export("顾客管理", result, columns, Response, Excel.PageType.handler);
            }
        }

        /// <summary>
        /// 查询当前店铺可管理用户
        /// </summary>
        [Exp2Client]
        public void GetCustomer4Vip()
        {
            var cardNo = P("cardNo");
            var customerName = P("customerName");
            var mobileOrPhone = P("mobileOrPhone");
            var sqlBuilder = new StringBuilder();
            sqlBuilder.AppendFormat(" shop_code in(select shop_code from sys_user_shop where user_key='{0}')",
                                    bllSYS_USER.CurrentUser.USER_KEY);
            if (cardNo != "") sqlBuilder.AppendFormat(" and card_no='{0}'", cardNo);
            if (customerName != "") sqlBuilder.AppendFormat(" and [name]='{0}'", customerName);
            if (mobileOrPhone != "") sqlBuilder.AppendFormat(" and ([mobile]='{0}' or phone='{0}')", mobileOrPhone);
            var rslt = Manager.GetListArray(sqlBuilder.ToString());
            Response.Write(new ResponseInf
            {
                Success = true,
                Data = (from CUSTOMERinfo cur in rslt
                        select new
                        {
                            CustomerKey = cur.CUSTOMER_KEY.ToString(),
                            Name = cur.NAME,
                            Mobile = cur.MOBILE,
                            CardNo = cur.CARD_NO,
                            Phone = cur.PHONE
                        }).ToList()
            }.ToJson());
        }

        /// <summary>
        /// 添加/编辑顾客信息
        /// </summary>
        [Exp2Client]
        public void EditCustomer()
        {
            var curstomerJson = P("curstomer");
            var memDateJson = P("memDates");
            var mems = JsonSerializer.Deserialize<List<MemDayInfo>>(memDateJson);
            var clientObj = JsonSerializer.Deserialize<CurstomerInfo>(curstomerJson);
            var photo_url = P("photo_url");

            var obj = BuildCurstomer(clientObj);
            if (clientObj.CUSTOMER_KEY.IsGuidB())
            {//Edit
                obj.CUSTOMER_KEY = clientObj.CUSTOMER_KEY.ToGuid();
                var serverObj = Manager.GetModel(obj.CUSTOMER_KEY);
                obj.GIVE_POINTS = serverObj.GIVE_POINTS;
                obj.CONSUME_POINTS = serverObj.CONSUME_POINTS;
                if (!string.IsNullOrEmpty(serverObj.CARD_NO)) obj.CARD_NO = serverObj.CARD_NO;
                obj.STATUS = serverObj.STATUS;
                obj.SHOP_CODE = serverObj.SHOP_CODE;
                obj.USER_CREATE = serverObj.USER_CREATE;
                obj.DATE_CREATE = serverObj.DATE_CREATE;
                obj.LATEST_CALL_DATE = serverObj.LATEST_CALL_DATE;
                obj.LATEST_SMS_DATE = serverObj.LATEST_SMS_DATE;
                obj.STORED_MONEY = serverObj.STORED_MONEY;
                Manager.Update(obj);
                bllCUSTOMER_DISEASE.RemoveByCustomer(obj.CUSTOMER_KEY);
                foreach (var dis in clientObj.DISEASE)
                {
                    Disease.Add(new CUSTOMER_DISEASEinfo()
                    {
                        ID = Guid.NewGuid(),
                        CUSTOMER_KEY = obj.CUSTOMER_KEY,
                        CODE = dis.Code,
                        NAME = dis.Name,
                        DATE_CREATE = DateTime.Now,
                        DATE_UPDATE = DateTime.Now,
                    });
                }
                AppendLog(serverObj, obj, LogType.Edit);
            }
            else
            {
                obj.CUSTOMER_KEY = DB.HR.GetNewGuid().ToGuid();
                obj.SHOP_CODE = bllSYS_USER.CurrentUser.SHOP_CODE;
                obj.USER_CREATE = bllSYS_USER.CurrentUser.USER_KEY;
                obj.STATUS = "1";
                Manager.Add(obj);
                AppendLog(obj, null, LogType.Add);

                var memDates = BuildCustomerMemoInfo(mems);
                //Add memDate
                foreach (var memDate in memDates)
                {
                    memDate.ID = Guid.NewGuid();
                    memDate.CUSTOMER_KEY = obj.CUSTOMER_KEY;
                    MemoDay.Add(memDate);
                }

                //Add Disea
                foreach (var dis in clientObj.DISEASE)
                {
                    Disease.Add(new CUSTOMER_DISEASEinfo()
                    {
                        ID = Guid.NewGuid(),
                        CUSTOMER_KEY = obj.CUSTOMER_KEY,
                        CODE = dis.Code,
                        NAME = dis.Name,
                        DATE_CREATE = DateTime.Now,
                        DATE_UPDATE = DateTime.Now,
                    });
                }
            }
            Manager.AddPhoto(obj.CUSTOMER_KEY.ToString(), photo_url);

            var dicBll = new bllDIC_LEVEL();
            var lev = dicBll.GetModel(obj.LEVEL_CODE);
            var group = groupMgr.GetModel(obj.GROUP_KEY);
            var blShop = shopMgr.GetModel(obj.SHOP_CODE);
            Response.Write(JsonSerializer.Serialize(new ResponseInf
            {
                Success = true,
                Data = new
                {
                    CUSTOMER_KEY = obj.CUSTOMER_KEY.ToString(),
                    CARD_NO = obj.CARD_NO,
                    NAME = obj.NAME,
                    MOBILE = obj.MOBILE,
                    LEVEL_CODE = obj.LEVEL_CODE,
                    BIRTHDAY = obj.BIRTHDAY.ToShortDateLineFormat(),
                    LEVEL_NAME = lev != null ? lev.NAME : "",
                    AVAIPOINTS = obj.GIVE_POINTS + obj.CONSUME_POINTS,
                    STORED_MONEY = obj.STORED_MONEY,
                    DATE_CREATE = obj.DATE_CREATE.ToFullDateTimeFormat(),
                    GROUP_NAME = group != null ? group.NAME : "",
                    STATUS_NAME = (obj.STATUS == "1" ? "有效" : (obj.STATUS == "9" ? "已删除" : "")),
                    SHOP_NAME = (blShop != null) ? blShop.SHOP_NAME : "",
                    GIVE_POINTS = obj.GIVE_POINTS.ToString(),
                    CONSUME_POINT=obj.CONSUME_POINTS.ToString()
                }
            }));
        }

        /// <summary>
        /// 编辑或添加Memday
        /// </summary>
        [Exp2Client]
        public void EditMemDay()
        {
            var customerKey = P("customerKey");
            var memJson = P("memDay");
            if (!customerKey.IsGuidB()) throw new Exception("顾客编号不正确.");
            var mem = JsonSerializer.Deserialize<MemDayInfo>(memJson);
            var curMem = BuildCustomerMemoInfo(mem);

            if (curMem != null)
            {
                if (curMem.ID == Guid.Empty)
                {
                    //New Mem Day
                    curMem.ID = Guid.NewGuid();
                    curMem.CUSTOMER_KEY = customerKey.ToGuid();
                    MemoDay.Add(curMem);
                }
                else
                {
                    //Edit Mem Day
                    var dbMemDay = MemoDay.GetModel(curMem.ID);
                    if (null == dbMemDay)
                    {
                        curMem.DATE_CREATE = DateTime.Now;
                        curMem.DATE_UPDATE = DateTime.Now;
                        MemoDay.Add(curMem);
                    }
                    else
                    {
                        curMem.DATE_CREATE = dbMemDay.DATE_CREATE;
                        curMem.DATE_UPDATE = DateTime.Now;
                        curMem.ID = dbMemDay.ID;
                        curMem.CUSTOMER_KEY = dbMemDay.CUSTOMER_KEY;
                        MemoDay.Update(curMem);
                    }
                }
                mem.Id = curMem.ID.ToString();
            }
            Response.Write(new ResponseInf { Success = true, Data = mem }.ToJson());
        }

        /// <summary>
        /// 顾客卡号是否存在
        /// </summary>
        [Exp2Client]
        public void CardNoExists()
        {
            var cardNo = P("cardNo");
            var customerKey = P("customerKey");
            Response.Write(new ResponseInf { Success = true, Data = Manager.CardNoExists(cardNo, customerKey) }.ToJson());
        }

        /// <summary>
        /// 检测手机号是否存在
        /// </summary>
        [Exp2Client]
        public void MobileExists()
        {
            var mobile = P("mobile");
            var customerKey = P("customerKey");
            Response.Write(new ResponseInf { Success = true, Data = Manager.MobileExists(mobile, customerKey) }.ToJson());
        }

        /// <summary>
        /// 更换卡号
        /// </summary>
        [Exp2Client]
        public void ChangeCardNo()
        {
            var newCardNo = P("cardNo").Trim();
            var customerKey = P("customerKey");
            var levelCode = P("levelCode");

            if (customerKey.IsGuidB())
            {
                var curstomer = Manager.GetModel(customerKey.ToGuid());
                if (curstomer == null) throw new Exception(string.Format("编号为\"{0}\"的用户不存在.", customerKey));
                if (!string.IsNullOrEmpty(newCardNo) && Manager.CardNoExists(newCardNo, customerKey)) throw new Exception(string.Format("卡号\"{0}\"已存在.", newCardNo));
                var cardChange = new CUSTOMER_CARD_CHANGEinfo()
                {
                    CUSTOMER_KEY = curstomer.CUSTOMER_KEY,
                    USER_CREATE = bllSYS_USER.CurrentUser.USER_KEY,
                    DATE_CHANGE = DateTime.Now,
                    DATE_CREATE = DateTime.Now,
                    DATE_UPDATE = DateTime.Now,
                    ID = DB.HR.GetNewGuid().ToGuid(),
                    NEW_CARD = !string.IsNullOrEmpty(newCardNo) ? newCardNo : curstomer.CARD_NO,
                    OLD_CARD = curstomer.CARD_NO,
                    NEW_LEVEL = levelCode,
                    OLD_LEVEL = curstomer.LEVEL_CODE
                };
                if (!string.IsNullOrEmpty(newCardNo)) curstomer.CARD_NO = newCardNo;
                curstomer.LEVEL_CODE = levelCode;
                curstomer.DATE_UPDATE = DateTime.Now;
                Manager.Update(curstomer);
                AppendLog(new CUSTOMERinfo()
                    {
                        CUSTOMER_KEY = curstomer.CUSTOMER_KEY,
                        NAME = curstomer.NAME,
                        MOBILE = curstomer.MOBILE,
                        CARD_NO = cardChange.OLD_CARD,
                        LEVEL_CODE = cardChange.OLD_LEVEL
                    }, new CUSTOMERinfo()
                    {
                        CUSTOMER_KEY = curstomer.CUSTOMER_KEY,
                        NAME = curstomer.NAME,
                        MOBILE = curstomer.MOBILE,
                        CARD_NO = cardChange.NEW_CARD,
                        LEVEL_CODE = cardChange.NEW_LEVEL
                    }, LogType.Edit);
                CardChangeMgr.Add(cardChange);

                Response.Write(new ResponseInf
                {
                    Success = true,
                    Data = new
                        {
                            CardNo = !string.IsNullOrEmpty(newCardNo) ? newCardNo : curstomer.CARD_NO,
                            LevelCode = levelCode
                        }
                }.ToJson());
                return;
            }
            throw new Exception("顾客编号格式不正确.");
        }

        /// <summary>
        /// 更换店面
        /// </summary>
        [Exp2Client]
        public void ChangeShop()
        {
            var shopCode = P("shopCode");
            var customerKey = P("customerKey");
            try
            {
                if (customerKey.IsGuidB())
                {
                    var curstomer = Manager.GetModel(customerKey.ToGuid());
                    if (curstomer == null) throw new Exception(string.Format("编号为\"{0}\"的用户不存在.", customerKey));
                    var shopbll = new bllSHOP();
                    if (!shopbll.Exists(shopCode)) throw new Exception(string.Format("编号为\"{0}\"的店面不存在.", shopCode));
                    curstomer.SHOP_CODE = shopCode;
                    curstomer.DATE_UPDATE = DateTime.Now;
                    Manager.Update(curstomer);
                    AppendLog(new CUSTOMERinfo()
                    {
                        CUSTOMER_KEY = curstomer.CUSTOMER_KEY,
                        NAME = curstomer.NAME,
                        MOBILE = curstomer.MOBILE,
                        SHOP_CODE = curstomer.SHOP_CODE
                    }, new CUSTOMERinfo()
                    {
                        CUSTOMER_KEY = curstomer.CUSTOMER_KEY,
                        NAME = curstomer.NAME,
                        MOBILE = curstomer.MOBILE,
                        SHOP_CODE = shopCode
                    }, LogType.Edit);
                    Response.Write(new ResponseInf
                    {
                        Success = true,
                        Data = shopCode
                    }.ToJson());
                    return;
                }
                throw new Exception("顾客编号格式不正确.");
            }
            catch (Exception exp)
            {
                Response.Write(new ResponseInf { Success = false, Message = exp.Message }.ToJson());
            }
        }

        /// <summary>
        /// 
        /// </summary>
        [Exp2Client]
        public void GetCustomerNameByCard_No()
        {
            var cardNo = P("cardNo");
            var customers = Manager.GetListArray(string.Format(" CARD_NO='{0}' ", cardNo));
            Response.Write(new ResponseInf { Success = true, Data = (customers != null && customers.Count > 0) ? customers[0].NAME : "" }.ToJson());
        }

        /// <summary>
        /// 删除一个Curstomer
        /// </summary>
        [Exp2Client]
        public void RemoveCustomer()
        {
            var curstomerKey = P("customerKey");
            if (curstomerKey.IsGuidB())
            {
                var module = Manager.GetModel(curstomerKey.ToGuid());
                if (module != null)
                {
                    if (module.STATUS == "4") throw new Exception("此顾客不允许被删除.");
                    //module.STATUS = "9";
                    //module.DATE_UPDATE = DateTime.Now;
                    //Manager.Update(module);
                    Manager.DeleteCustomer(module.CUSTOMER_KEY);
                    //bllCUSTOMER_DISEASE.RemoveByCustomer(curstomerKey.ToGuid());
                    AppendLog(module, null, LogType.Delete);
                    Response.Write(new ResponseInf { Success = true }.ToJson());
                    return;
                }
            }
            throw new Exception("客户不存在.");
        }

        /// <summary>
        /// 查询顾客手机号
        /// </summary>
        [Exp2Client]
        public void SearchCustomerMobile()
        {
            var searchOpt = JsonSerializer.Deserialize<CustomerMobileJson>(P("srchJson"));
            int tmpInt;
            DateTime tmpDateTime;
            var rslt = bllCUSTOMER.GetCustomer4MobileSelect(searchOpt.CARD_NO, searchOpt.CARD_NAME,
                                                            DateTime.TryParse(searchOpt.MEMODAY_FROM, out tmpDateTime)
                                                                ? tmpDateTime
                                                                : new DateTime?(),
                                                            DateTime.TryParse(searchOpt.MEMODAY_TO, out tmpDateTime)
                                                                ? tmpDateTime
                                                                : new DateTime?(),
                                                            searchOpt.CUSTOMER_LEVEL, searchOpt.CUSTOMER_GENDER,
                                                            int.TryParse(searchOpt.AGE_FROM, out tmpInt)
                                                                ? tmpInt
                                                                : new int?(),
                                                            int.TryParse(searchOpt.AGE_TO, out tmpInt)
                                                                ? tmpInt
                                                                : new int?(),
                                                            int.TryParse(searchOpt.POINT_FROM, out tmpInt)
                                                                ? tmpInt
                                                                : new int?(),
                                                            int.TryParse(searchOpt.POINT_TO, out tmpInt)
                                                                ? tmpInt
                                                                : new int?(),
                                                            searchOpt.AREA_CODE,
                                                            searchOpt.SHOP_CODES,
                                                            bllSYS_USER.CurrentUser.USER_KEY.ToString(),
                                                            searchOpt.RemoveNoMobile,
                                                            searchOpt.MOBILE_NUM,
                                                            searchOpt.SHOP_CODE
                );

            Response.Write(new ResponseInf
            {
                Success = true,
                Data = (from t in rslt.AsEnumerable()
                        select new
                            {
                                CUSTOMER_KEY = t.Field<Guid>("CUSTOMER_KEY").ToString(),
                                CARD_NO = t.Field<string>("CARD_NO"),
                                NAME = t.Field<string>("NAME"),
                                MOBILE = t.Field<string>("MOBILE"),
                            }).ToList()
            }.ToJson());
        }

        /// <summary>
        /// 删除用户的纪念日
        /// </summary>
        [Exp2Client]
        public void RemoveMemo()
        {
            var pk = P("memKey");
            if (!pk.IsGuidB()) throw new Exception("顾客纪念日编号格式不正确.");
            MemoDay.Delete(pk.ToGuid());
            Response.Write(new ResponseInf { Success = true }.ToJson());
        }
        #endregion


        public CUSTOMERinfo BuildCurstomer(CurstomerInfo info)
        {
            var curstomer = new CUSTOMERinfo();
            curstomer.CUSTOMER_KEY = (info.CUSTOMER_KEY.IsGuidB()) ? new Guid(info.CUSTOMER_KEY) : Guid.Empty;
            curstomer.ADDRESS = info.ADDRESS.Trim();
            curstomer.AREA_CODE = info.AREA_CODE;
            curstomer.CARD_NO = info.CARD_NO;
            curstomer.EMAIL = info.EMAIL;
            DateTime tmpDate;
            int tmpInt;
            if (DateTime.TryParse(info.BIRTHDAY, out tmpDate)) curstomer.BIRTHDAY = tmpDate;
            if (int.TryParse(info.CONSUME_POINTS, out tmpInt)) curstomer.CONSUME_POINTS = tmpInt;
            if (int.TryParse(info.GIVE_POINTS, out tmpInt)) curstomer.GIVE_POINTS = tmpInt;
            if (info.GROUP_KEY.IsGuidB()) curstomer.GROUP_KEY = new Guid(info.GROUP_KEY);
            info.GROUP_KEY = null;
            curstomer.ID_CARD = info.ID_CARD;
            curstomer.IS_LUNAR_CALENDAR = info.IS_LUNAR_CALENDAR;
            if (info.LEVEL_CODE == "") throw new Exception("请选择顾客级别");
            curstomer.LEVEL_CODE = info.LEVEL_CODE;
            curstomer.MEMO = info.MEMO;
            curstomer.MOBILE = info.MOBILE;
            curstomer.NAME = info.NAME;
            curstomer.POSTAL_CODE = info.POSTAL_CODE;
            curstomer.PWD = info.PWD;
            curstomer.REFEREE = info.REFEREE;
            curstomer.DISEASE = "";
            curstomer.REFEREE_CARD = info.REFEREE_CARD;
            curstomer.SEX = info.SEX;
            curstomer.PHONE = info.PHONE;
            curstomer.FAMILY = info.FAMILY;
            curstomer.TITLE = info.TITLE;
            //curstomer.SHOP_CODE = bllSYS_USER.CurrentUser.SHOP_CODE;
            //curstomer.STATUS = "0";
            //curstomer.USER_CREATE = bllSYS_USER.CurrentUser.USER_KEY;
            curstomer.DATE_UPDATE = DateTime.Now;
            curstomer.DATE_CREATE = DateTime.Now;
            return curstomer;
        }

        /// <summary>
        /// 创建CustomerMem info对象
        /// </summary>
        /// <param name="mems"></param>
        /// <returns></returns>
        public List<CUSTOMER_MEMORIALDAYinfo> BuildCustomerMemoInfo(List<MemDayInfo> mems)
        {
            var lst = new List<CUSTOMER_MEMORIALDAYinfo>();
            DateTime dtTmp;
            CUSTOMER_MEMORIALDAYinfo tmp;
            foreach (var mem in mems)
            {
                tmp = BuildCustomerMemoInfo(mem);
                if (tmp != null) lst.Add(tmp);
            }
            return lst;
        }

        public CUSTOMER_MEMORIALDAYinfo BuildCustomerMemoInfo(MemDayInfo mem)
        {
            DateTime dtTmp;
            return (DateTime.TryParse(mem.Date, out dtTmp)) ?
            new CUSTOMER_MEMORIALDAYinfo()
            {
                NAME = mem.Name,
                MEMORIALDAY_DATE = dtTmp,
                ID = mem.Id.IsGuidB() ? mem.Id.ToGuid() : Guid.Empty
            } : null;
        }

        public CustomerMobileInfo GetCustomerMobileSearchOpt(CustomerMobileJson jsonObj)
        {
            DateTime dtTmp;
            var rslt = new CustomerMobileInfo();
            rslt.CARD_NO = jsonObj.CARD_NO.Trim();
            rslt.CARD_NAME = jsonObj.CARD_NAME.Trim();
            rslt.MEMODAYTYPE = jsonObj.MEMODAYTYPE.Trim();
            return null;
        }

        /// <summary>
        /// 获取顾客信息,需要加上当前用户ID条件
        /// </summary>
        public void GetTermCustomer()
        {
            try
            {
                var customer_card_or_name_mobile = P("term"); // 此插件提供的默认的参数名称
                var select_term = P("select_term");
                string condition1 = string.Format(@" shop_code in(  select b.shop_code 
from   dbo.SYS_USER a inner join sys_user_shop b on a.user_key=b.user_key where b.user_key='{0}')", bllSYS_USER.CurrentUser.USER_KEY.ToString()); // 当前账户下的店面
                string condition2 = string.Empty;
                if (select_term == "CARD_NO")
                {
                    condition2 = String.Format(" and  CARD_NO LIKE '%{0}%' ", customer_card_or_name_mobile); // 根据用户输入的条件来进行模糊查询
                }
                else if (select_term == "NAME")
                {
                    condition2 = String.Format(" and  NAME LIKE '%{0}%' ", customer_card_or_name_mobile);
                }
                else
                {//MOBILE
                    condition2 = String.Format(" and  MOBILE LIKE '%{0}%' ", customer_card_or_name_mobile);
                }
                List<CUSTOMERinfo> customerList = Manager.GetListArray(condition1 + condition2);
                if (customerList.Count == 0)
                {
                    customerList.Add(new CUSTOMERinfo() { CARD_NO = "XXXXXXXX", NAME = "抱歉，没有对应顾客！", MOBILE = "00000000000" });
                }
                //Response.Write(JsonSerializer.Serialize(new ResponseInf { MessageCode = "Ok", Data = shopList.ToArray() }));
                Response.Write(JsonSerializer.Serialize(customerList));
            }
            catch (Exception exp)
            {
                Response.Write(JsonSerializer.Serialize(new ResponseInf { MessageCode = "Error", Message = exp.Message.FilterJs() }));
            }
        }

        #region Class
        public class CurstomerInfo
        {
            public string CUSTOMER_KEY;
            public string CARD_NO;
            public string LEVEL_CODE;
            public string NAME;
            public string MOBILE;
            public string ID_CARD;
            public string SEX;
            public string BIRTHDAY;
            public string IS_LUNAR_CALENDAR;
            public string REFEREE_CARD;
            public string REFEREE;
            public string AREA_CODE;
            public string ADDRESS;
            public string POSTAL_CODE;
            public string EMAIL;
            public string GIVE_POINTS;
            public string CONSUME_POINTS;
            public string GROUP_KEY;
            public string PWD;
            public string MEMO;
            public List<CodeName> DISEASE;
            public string PHONE;
            public string TITLE;
            public string FAMILY;
        }

        public class MemDayInfo
        {
            public string Id;
            public string Name;
            public string Date;
        }

        public class AdvanceSearchJson
        {
            public string CARD_NO;
            public string LEVEL_CODE;
            public string NAME;
            public string SEX;
            public string REFEREE_CARD;
            public string REFEREE;
            public string ID_CARD;
            public string AGEFROM;
            public string AGETO;
            public string MOBILE;
            public string PHONE;
            public string AREA_CODE;
            public string DATE_CREATESTART;
            public string DATE_CREATEEND;
            public string AVAPOINTFROM;
            public string AVAPOINTTO;
            public string GROUP_KEY;
            public string BIRTHDAYTO;
            public string BIRTHDAYFROM;
            public string LEVEL_NAME;
            public string GROUP_NAME;
            public string CITY;
            public string PROVINCE;
            public string CITY_NAME;
            public string PROVINCE_NAME;
            public string AREA_NAME;
            public string TITLE;
            public string FAMILY;
        }

        /// <summary>
        /// 添加短信时选择窗体查询条件
        /// </summary>
        public class CustomerMobileJson
        {
            public string CARD_NO;
            public string CARD_NAME;
            public string MEMODAYTYPE;
            public string MEMODAY_FROM;
            public string MEMODAY_TO;
            public string CUSTOMER_LEVEL;
            public string CUSTOMER_GENDER;
            public string AGE_FROM;
            public string AGE_TO;
            public string POINT_FROM;
            public string POINT_TO;
            public string AREA_CODE;
            public bool RemoveNoMobile;
            public string SHOP_CODES;//,分割
            public string MOBILE_NUM;
            public string SHOP_CODE;
        }

        public class CustomerMobileInfo
        {
            public string CARD_NO;
            public string CARD_NAME;
            public string MEMODAYTYPE;
            public DateTime? MEMODAY_FROM;
            public DateTime? MEMODAY_To;
            public string CUSTOMER_LEVEL;
            public string GENDER;
            public int? AGEF_ROM;
            public int? AGE_TO;
            public int? POINT_FROM;
            public int? POINT_TO;
            public string AREA_CODE;
            public bool NotIncludeNoMobile;
        }

        public class CodeName
        {
            public string Code;
            public string Name;
        }
        #endregion

        #region Log

        private static string modeCode = "003001002";
        /// <summary>
        /// 添加Customer部分日志
        /// </summary>
        /// <param name="from"></param>
        /// <param name="to"></param>
        /// <param name="logType"></param>
        private void AppendLog(CUSTOMERinfo from, CUSTOMERinfo to, LogType logType)
        {
            if (logType == LogType.Add)
            {
                bllSYS_LOG.SaveLog(modeCode,
                    "CUSTOMER",
                    from.CUSTOMER_KEY.ToString(),
                    string.Format("添加顾客，顾客姓名:\"{0}\"  手机号:\"{1}\"", from.NAME, from.MOBILE),
                    "添加",
                    BusinessBase.ClientIp);
                return;
            }
            if (logType == LogType.Edit)
            {
                builder.Clear();
                builder.AppendFormat("修改顾客，顾客姓名：\"{0}\"  手机号：\"{1}\"", from.NAME, from.MOBILE);
                var bChange = false;
                if (from.NAME != to.NAME)
                {
                    builder.AppendFormat("顾客姓名原值:\"{0}\"，现值:\"{1}\"", from.NAME, to.NAME);
                    bChange = true;
                }
                if (from.LEVEL_CODE != to.LEVEL_CODE)
                {
                    var levelMgr = new bllDIC_LEVEL();
                    var levelF = levelMgr.GetModel(from.LEVEL_CODE);
                    var levelT = levelMgr.GetModel(to.LEVEL_CODE);
                    builder.AppendFormat("顾客级别原值:\"{0}\"，现值:\"{1}\"", (levelF != null ? levelF.NAME : ""), (levelT != null ? levelT.NAME : ""));
                    bChange = true;
                }
                if (from.MOBILE != to.MOBILE)
                {
                    builder.AppendFormat("顾客手机号原值:\"{0}\"，现值:\"{1}\"", from.MOBILE, to.MOBILE);
                    bChange = true;
                }
                if (from.SEX != to.SEX)
                {
                    builder.AppendFormat("顾客性别原值:\"{0}\"，现值:\"{1}\"", (from.SEX == "1" ? "男" : "女"), (to.SEX == "1" ? "男" : "女"));
                    bChange = true;
                }
                if (from.GROUP_KEY != to.GROUP_KEY)
                {
                    groupMgr = groupMgr ?? new bllDIC_GROUP();
                    var groupF = groupMgr.GetModel(from.GROUP_KEY);
                    var groupT = groupMgr.GetModel(to.GROUP_KEY);
                    builder.AppendFormat("顾客分组原值:\"{0}\"，现值:\"{1}\"", (groupF != null ? groupF.NAME : ""), (groupT != null ? groupT.NAME : ""));
                    bChange = true;
                }
                if (from.BIRTHDAY != to.BIRTHDAY)
                {
                    builder.AppendFormat("顾客生日原值:\"{0}\"，现值:\"{1}\"", from.BIRTHDAY.ToShortDateLineFormat(), to.BIRTHDAY.ToShortDateLineFormat());
                    bChange = true;
                }
                if (from.SHOP_CODE != to.SHOP_CODE)
                {
                    shopMgr = shopMgr ?? new bllSHOP();
                    var shopF = groupMgr.GetModel(from.GROUP_KEY);
                    var shopT = groupMgr.GetModel(to.GROUP_KEY);
                    builder.AppendFormat("顾客店铺原值:\"{0}\"，现值:\"{1}\"", (shopF != null ? shopF.NAME : ""), (shopT != null ? shopT.NAME : ""));
                    bChange = true;
                }
                if (from.CARD_NO != to.CARD_NO)
                {
                    builder.AppendFormat("顾客卡号原值:\"{0}\"，现值:\"{1}\"", from.CARD_NO, to.CARD_NO);
                    bChange = true;
                }
                if (bChange)
                {
                    bllSYS_LOG.SaveLog(modeCode,
                      "CUSTOMER",
                      from.CUSTOMER_KEY.ToString(),
                      builder.ToString(),
                      "修改",
                      BusinessBase.ClientIp);
                }
                return;
            }
            if (logType == LogType.Delete)
            {
                bllSYS_LOG.SaveLog(modeCode,
                      "CUSTOMER",
                      from.CUSTOMER_KEY.ToString(),
                      string.Format("删除顾客，顾客姓名:\"{0}\"  手机号:\"{1}\"", from.NAME, from.MOBILE),
                      "删除",
                      BusinessBase.ClientIp);
            }
        }
        #endregion
    }
}
